<template>
    <div>
        <div class="flex justify-between items-center">
            <el-space>
                <el-select
                    placeholder="请选择设备"
                    filterable
                    v-model="currentMachine"
                    @change="onChange"
                >
                    <el-option
                        v-for="item in productCategory"
                        :key="item.key"
                        :label="item.name"
                        :value="item.ip"
                    />
                </el-select>
                <el-space>
                    <el-date-picker
                        v-model="date"
                        type="daterange"
                        start-placeholder="起始"
                        end-placeholder="截止"
                        :clearable="false"
                        :default-value="[new Date(), new Date()]"
                        @change="onDatePicked"
                    />
                </el-space>
                <el-button
                    type="primary"
                    :icon="Search"
                    @click="getUsageRecord()"
                    >搜索</el-button
                >
            </el-space>
            <el-space>
                <el-button type="primary" @click="ExportUsageRecord"
                    >导出记录</el-button
                >
            </el-space>
        </div>
        <div class="flex-1 flex flex-col pt-5">
            <el-table
                v-loading="loading"
                element-loading-text="加载中"
                stripe
                border
                :data="returnData"
                style="width: 100%; height: calc(100vh - 9rem)"
                cell-class-name="cell-wrapper"
            >
                <el-table-column
                    label="序号"
                    min-width="80"
                    align="center"
                    type="index"
                />
                <el-table-column
                    resizable
                    v-for="[prop, label, formatter, fixed] in tableKV"
                    :key="prop"
                    :fixed="fixed"
                    :prop="prop"
                    :label="label"
                    :formatter="formatter"
                    align="center"
                ></el-table-column>
                <el-table-column label="操作" align="center" min-width="60">
                    <template #default="{ row }">
                        <el-space>
                            <el-popconfirm
                                width="220"
                                confirm-button-text="确认"
                                cancel-button-text="取消"
                                :icon="InfoFilled"
                                icon-color="red"
                                :title="`确认删除 ${row.userName}`"
                                @confirm="
                                    () => deleteRecords(row.UsageRecordId)
                                "
                            >
                                <template #reference>
                                    <el-button type="danger" size="default"
                                        >删除</el-button
                                    >
                                </template>
                            </el-popconfirm>
                        </el-space>
                    </template>
                </el-table-column>
            </el-table>
        </div>

        <div class="flex justify-end mt-4">
            <el-pagination
                :current-page="pagination.pageIndex"
                :page-size="pagination.pageSize"
                :page-sizes="[10, 20]"
                layout="sizes, prev, pager, next"
                :total="pagination.altogether"
                @current-change="onCurrentChange"
                @size-change="onSizeChange"
            />
        </div>
    </div>
</template>


<script setup>
import { h, reactive, ref, onMounted } from 'vue'
import DataRecords from '@/api/record/DataRecords'
import { requestedMessage } from '@/utils/asynchronous'
import { InfoFilled, Search } from '@element-plus/icons-vue'
import { EXCEL_TYPE } from '@/common/names'
import { ElAvatar } from 'element-plus'
import ExcelJS from 'exceljs'
import FileSaver from 'file-saver'
import moment from 'moment'
import { ElLoading, ElMessage } from 'element-plus'

/**
 *  返回数据
 */
const returnData = ref([])
/**
 * 加载
 */
const loading = ref(false)
/**
 * 设备地址
 */
const productCategory = JSON.parse(localStorage.getItem('machine'))
const currentMachine = ref(productCategory[0].ip)

/**
 * 分页信息
 */
const pagination = {
    pageIndex: 1,
    pageSize: 10,
    altogether: 0
}

/**
 * 时间选择
 */
const now = new Date()
const start = new Date(
    now.getFullYear(),
    now.getMonth(),
    now.getDate(),
    0,
    0,
    0,
    0
)
const end = new Date(
    now.getFullYear(),
    now.getMonth(),
    now.getDate() + 1,
    0,
    0,
    0,
    -1
)
const date = ref([start, end])

/**
 * 修正选择后的结束日期时间戳
 * @param {*} d
 */
function onDatePicked(d) {
    d[1].setHours(23)
    d[1].setMinutes(59)
    d[1].setSeconds(59, 999)
    date.value = d
    getUsageRecord()
}
/**
 * 展示数据和标题
 */
const tableKV = [
    ['boxNum', '门号'],
    ['SaveOrTake', '存物方式'],
    ['userName', '姓名'],
    ['userSex', '性别'],
    ['IdentityCardNumber', '身份证号码'],
    [
        'base64ImagePath',
        '照片',
        (row, column, cellValue, index) =>
            h(ElAvatar, {
                shape: 'square',
                size: 60,
                fit: 'cover',
                style: 'background:transparent',
                src: `data:image/png;base64,${row.base64ImagePath}`
            })
    ],
    [
        'openTime',
        '开门时间',
        (row, column, cellValue, index) => formatDate(cellValue)
    ]
]

/**
 *  事件来处理页码大小和当前页变动时候触发的事件
 *  改变时触发
 * @param {*} num
 */
function onCurrentChange(num) {
    pagination.pageIndex = num
    /**
     * 获取查询列表
     */
    getUsageRecord()
}
/**
 * 使用了 size-change 和 current-change 事件来处理页码大小和当前页变动时候触发的事件
 * 改变时触发
 * @param {*} num
 */
function onSizeChange(num) {
    pagination.pageIndex = 1
    pagination.pageSize = num
    /**
     * 获取查询列表
     */
    getUsageRecord()
}

onMounted(() => {
    /**
     * 获取查询列表
     */
    getUsageRecord()
})

/**
 * 查询列表
 */
function getUsageRecord() {
    requestedMessage(
        async () => {
            loading.value = true
            const { message, msg, totality } = await DataRecords.getUsageRecord(
                currentMachine.value,
                {
                    startTime: +date.value[0],
                    endTime: +date.value[1],
                    pageIndex:
                        pagination.pageIndex == 1
                            ? pagination.pageIndex - 1
                            : (pagination.pageIndex - 1) * pagination.pageSize,
                    pageSize: pagination.pageSize
                }
            )
            pagination.altogether = totality
            if (message != '') {
                returnData.value = message
            }

            return msg
        },
        {
            showSuccess: false,
            fullscreenLoading: false,
            finalHandle: () => {
                loading.value = false
            }
        }
    )
}
/**
 * 切换
 * @param {*} v
 */
function onChange(v) {
    getUsageRecord()
}

/**
 * 时间戳转日期
 * @param {*} date
 */
function formatDate(date) {
    const formattedDate = new Date(date)
    const year = formattedDate.getFullYear()
    const month = String(formattedDate.getMonth() + 1).padStart(2, '0')
    const day = String(formattedDate.getDate()).padStart(2, '0')
    const hours = String(formattedDate.getHours()).padStart(2, '0')
    const minutes = String(formattedDate.getMinutes()).padStart(2, '0')
    const seconds = String(formattedDate.getSeconds()).padStart(2, '0')
    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
}
/**
 * 删除记录
 * @param {*} UsageRecordId
 */
function deleteRecords(UsageRecordId) {
    requestedMessage(async () => {
        const { msg } = await DataRecords.deleteRecords(currentMachine.value, {
            UsageRecordId: UsageRecordId
        })
        getUsageRecord()
        return msg
    })
}

/**
 * 导出使用记录
 */
async function ExportUsageRecord() {
    const load = ElLoading.service({
        lock: true,
        text: '正在拉取数据并进行导出',
        background: 'rgba(0, 0, 0, 0.7)'
    })

    const workbook = new ExcelJS.Workbook()
    const columns = tableKV
        .map(([key, header]) => {
            if (header.includes('身份证号码')) {
                return {
                    header,
                    key,
                    width: 25,
                    style: {
                        alignment: { vertical: 'middle', horizontal: 'center' },
                        font: {
                            name: 'Arial',
                            size: 12
                        }
                    }
                }
            } else if (header.includes('开门时间')) {
                return {
                    header,
                    key,
                    width: 25,
                    style: {
                        alignment: { vertical: 'middle', horizontal: 'center' },
                        font: {
                            name: 'Arial',
                            size: 12
                        }
                    }
                }
            }
            console.log(header)
            return {
                header,
                key,
                width: 18,
                style: {
                    alignment: { vertical: 'middle', horizontal: 'center' },
                    font: {
                        name: 'Arial',
                        size: 12
                    }
                }
            }
        })
        .filter((i) => i)

    const worksheet = workbook.addWorksheet(`使用记录`)
    worksheet.columns = columns
    let table = []
    await new Promise((resolve, reject) => {
        requestedMessage(
            async () => {
                const { message, msg } = await DataRecords.exportAllRecords(
                    currentMachine.value
                )
                if (message != '') {
                    table = message
                    ElMessage.success({
                        message: '导出完成'
                    })
                }
                resolve()
                return msg
            },
            {
                showSuccess: false,
                fullscreenLoading: false,
                finalHandle: load.close,
                errorHandle: () => {
                    reject()
                }
            }
        )
    })
    table.map((item) => {
        return {
            ...item,
            openTime: formatDate(item.openTime)
        }
    })
    worksheet.addRows(
        table.map((item) => {
            return {
                ...item,
                openTime: formatDate(item.openTime)
            }
        })
    )
    // 迭代所有行并设置样式
    worksheet.eachRow({ includeEmpty: false }, (row, rowNumber) => {
        row.height = rowNumber === 1 ? 45 : 30
    })
    // 获取当前时间的时间戳（毫秒级）
    let currentTimestamp = Date.now()
    workbook.xlsx.writeBuffer().then((data) => {
        const blob = new Blob([data], { type: EXCEL_TYPE })
        FileSaver.saveAs(
            blob,
            `${'使用记录'}_${moment(currentTimestamp).format(
                'YYYY-MM-DD HH:mm:ss'
            )}.xls`
        )
        load.close()
    })
}
</script>


<style scoped></style>